#!/bin/bash
# 
# This script is the
# This script allows renew the IP address of my server
# dyndns, launching a HTTP query into some web services
# for check that IP we have, as www.whatismyip.com,
# www.formyip.com, etc..
#

# ---------------------------------------------------------
#   Load and check the configuration
# ---------------------------------------------------------

  # Load config file
  ConfigFile=/usr/local/TECNOQUIA/etc/dynIP.cfg
  if [ ! -e $ConfigFile ] || [ ! -r $ConfigFile ]
  then
     echo "ERROR: I can't read the config file [$ConfigFile]" >&2
     exit 5
  fi
  . $ConfigFile
    
  
  # Check the directory that i must save the log files
  BaseDir=$DIRECTORY_LOG
  if [ ! -w $BaseDir ]
  then
     echo "ERROR: I can't write into [$BaseDir]. Check that exists and the permissions on this directory" >&2
     exit 6
  fi

  # For temporay files
  tmpFile=/tmp/renuevaIP-$$-$RANDOM

  # Log file with results that renovations in dyndns
  logFile=$BaseDir/renovations.log

  # File with the last IP
  ipFile=$BaseDir/lastIP 

  # Contains my actual IP
  MyIP="" 

  # Check that everyone can write into these files
  chmod a+w $logFile $ipFile 2>/dev/null >&2



# ---------------------------------------------------------
#   Functions
# ---------------------------------------------------------

download () {
  /usr/bin/wget \
      -O $tmpFile.dwn \
      -U "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.3) \
          Gecko/20030430 Debian/1.3-5" \
      "http://$1" >/dev/null 2>&1    
  return $?
}



# ---------------------------------------------------------
#   M A I N
# ---------------------------------------------------------

  # Verify the IP that i have
  if download 'www.whatismyip.com/automation/n09230945.asp'
  then
     MyIP=$(cat $tmpFile.dwn)
  elif  download 'checkip.dyndns.org' 
  then
     MyIP=$(cat  $tmpFile.dwn \
     | perl -ne 'print $1 if ($_=~ m/Current IP Address:\s([\d|\.]+)/);')
  elif download 'www.formyip.com'
  then
     MyIP=$(grep 'Your IP' $tmpFile.dwn \
     | head -1 \
     | perl -ne 'print $1 if ($_=~ m/Your IP is\s([\d|\.]+)/);')
  elif download 'whatsmyip.org'
  then
     MyIP=$(grep 'Your IP' $tmpFile.dwn \
     | head -1 \
     | perl -ne 'print $1 if ($_=~ m/Your IP is\s([\d|\.]+)/);')
  else
     exit 0
  fi
  
  # Get last known IP
  OldIP=`cat $ipFile 2>/dev/null`

  # Call to dyndns webservice for renew
  if [ "$MyIP" != "$OldIP" ] && [ "$MyIP" != "" ]
  then
     if download "${DYNDNS_USER_LOGIN}:${DYNDNS_PASSWORD}@members.dyndns.org/nic/update?system=dyndns&hostname=${DYNDNS_DOMAIN}&myip=$MyIP&wildcard=ON&mx=${DYNDNS_MX}&backmx=NO&offline=NO"
     then
        echo "[`date "+%d/%h/%y  %H:%M:%S"`] [`date '+%s'`] Result: `cat $tmpFile.dwn` " >> $logFile
        echo -n "$MyIP" > $ipFile
     fi
  fi
  
  # Delete temporary files 
  rm -f $tmpFile.*
